import { ref } from 'vue';
import SockJS from 'sockjs-client';
import { Client, type IMessage, type StompSubscription } from '@stomp/stompjs';

// WebSocket 连接状态类型
type ConnectionStatus = 'DISCONNECTED' | 'CONNECTING' | 'CONNECTED' | 'ERROR';

// WebSocket 服务
export function useWebSocket() {
    // 连接状态
    const status = ref<ConnectionStatus>('DISCONNECTED');
    // STOMP 客户端
    const stompClient = ref<Client | null>(null);
    // 订阅列表
    const subscriptions = ref<StompSubscription[]>([]);
    // 消息列表
    const messages = ref<Array<{from: string; content: string; timestamp: string}>>([]);
    
    /**
     * 连接到 WebSocket 服务器
     * @param url WebSocket 服务器地址
     * @param onConnected 连接成功回调
     */
    const connect = (url: string, onConnected?: () => void) => {
        status.value = 'CONNECTING';
        
        // 创建 SockJS 实例
        // const socket = new SockJS(url);
        // setupNativeWebSocketListeners(socket);


        // 创建 STOMP 客户端
        stompClient.value = new Client({
            // webSocketFactory: () => socket,
            // brokerURL: url,
            brokerURL: 'ws://localhost:8080/ws', // 直接使用WebSocket协议
            reconnectDelay: 5000,// 设置为 0 禁用重连
            // heartbeatIncoming: 13000,//server->client stomp应用层心跳
            heartbeatIncoming: 0,
            heartbeatOutgoing: 20000,//client->server
            //  heartbeatIncoming: 0,//server->client stomp应用层心跳
            // heartbeatOutgoing: 0,//client->server
            onConnect: () => {
                status.value = 'CONNECTED';
                console.log('WebSocket connected');
                if (onConnected) onConnected();

            },
            onStompError: (frame) => {
                console.error('WebSocket error:', frame);
                status.value = 'ERROR';
            },
            //触发条件： 仅主动调用 disconnect()
            //STOMP 协议层事件
            //典型用途：清理资源、正常退出逻辑
            onDisconnect: () => {
                status.value = 'DISCONNECTED';
                console.log('WebSocket disconnected');
            },
            debug: (str: string) => {
                console.log('in debug msg: ',str+formatDate(new Date()));
                
                // 捕获STOMP层面的心跳
                // if (str.includes('<<< PONG') || str.includes('>>> PING')) {
                //     console.log('STOMP heartbeat detected:', str);
                // }
                
                // 也可以捕获WebSocket层面的帧，实际上捕获不了，应该是浏览器内核处理了
                if (str.includes('WebSocket frame received') && 
                    (str.includes('opcode=PING') || str.includes('opcode=PONG'))) {
                    console.log('Raw WebSocket heartbeat detected:', str);
                }
            },
        
            //触发条件： 任何 WebSocket 关闭（包括意外）
            //WebSocket 底层事件,不依赖 Stomp
            //典型用途：错误处理、自动重连
            onWebSocketClose:()=>{
                status.value = 'DISCONNECTED';
                console.log('WebSocket CLOSED');
            }
        });

       
        
        stompClient.value.activate();
    };
    
    /**
     * 断开 WebSocket 连接
     */
    const disconnect = () => {
        if (stompClient.value) {
            // 取消所有订阅
            subscriptions.value.forEach(sub => sub.unsubscribe());
            subscriptions.value = [];
            // 断开连接
            stompClient.value.deactivate();
            stompClient.value = null;
        }
    };
    
    /**
     * 订阅消息
     * @param destination 目标地址
     * @param callback 消息回调
     */
    const subscribe = (destination: string, callback: (message: IMessage) => void) => {
        if (stompClient.value && status.value === 'CONNECTED') {
            const subscription = stompClient.value.subscribe(destination, callback);
            subscriptions.value.push(subscription);
        }
    };
    
    /**
     * 发送消息
     * @param destination 目标地址
     * @param body 消息体
     */
    const send = (destination: string, body: any) => {
        if (stompClient.value && status.value === 'CONNECTED') {
            stompClient.value.publish({
                destination,
                body: JSON.stringify(body)
            });
        }
    };



    
    return {
        status,
        messages,
        connect,
        disconnect,
        subscribe,
        send
    };
}

function formatDate(date:Date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  

//     console.log('in setupNativeWebSocketListeners');
    
//     // SockJS在建立连接后会提供WebSocket实例
//     sockJSClient.onopen = () => {
//       // 获取底层WebSocket实例
//       const ws = sockJSClient._transport.url 
//         ? sockJSClient._transport.ws 
//         : null;

//         console.log('in setupNativeWebSocketListeners sockJSClient._transport.url ',sockJSClient._transport.url );
        
      
//       if (ws) {
//         // 监听原生WebSocket消息
//         ws.onmessage = (event) => {
//           // 空消息通常是心跳
//           if (event.data === '') {
           
//             console.log('收到WebSocket原生心跳');
//           }
//         };
        
//         // 监听WebSocket关闭
//         ws.onclose = () => {
//           console.log('WebSocket已关闭');
          
//         };
        
//         // 监听WebSocket错误
//         ws.onerror = (error) => {
//           console.log('WebSocket错误'+ error.message);
//         };
//       } else {
//         console.warn('无法获取底层WebSocket实例，可能使用的是HTTP流传输');
//       }
//     };
    
//     sockJSClient.onclose = () => {
//       console.log('WebSocket已关闭');
//     };
//   };